package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mapper.UserMapper;
import cn.tedu.egweibo1.pojo.dto.UserDTO;
import cn.tedu.egweibo1.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo1.pojo.entity.User;
import cn.tedu.egweibo1.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 注册功能
     * @param userDTO
     * @return
     */
    @PostMapping("reg")
    public String reg(@RequestBody UserDTO userDTO){
        UserVO selectuser = userMapper.selectuser(userDTO.getUsername());
        if(selectuser!=null){
            return "用户名已存在";
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return "添加成功";
    }

    /**
     * 登录功能
     */
    @PostMapping("login")
    public String UserLogin(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
        UserVO selectuser = userMapper.selectuser(userLoginDTO.getUsername());
        if(selectuser == null){
            return "用户名错误";
        }
        if (selectuser.getPassword().equals(userLoginDTO.getPassword())){
            session.setAttribute("user",selectuser);
            return "登录成功";
        }
        return "密码错误";
    }

    /**
     * 获取当前用户登录功能
     */
    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        return userVO;
    }

    /**
     * 退出登录功能
     */
    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }


}
